//导入express
const express = require('express');
// 导入http模块
const http = require('http');
// 引入xml2js
const xml2js = require("xml2js");
const parse = new xml2js.Parser({ explicitArray: false });
const build = new xml2js.Builder({ rootName: 'xml', cdata: true, headless: true });
// 创建express服务器
const app = express();
// 注册路由
app.get('/', (req, res) => {
    // 接收微信服务器通过get方式发送的echostr参数, 并且原样返回给微信服务器
    var echostr = req.query.echostr;
    console.log('微信服务器请求了:' + echostr);
    res.send(echostr);
});
// 注册post路由, 接收微信发送的消息
app.post('/', (req, res) => {
    // console.log('您有新的微信消息, 请注意查收');
    var dataBuffer = [];
    req.on('data', function (chunk) {
        dataBuffer.push(chunk);
    });
    req.on('end', function () {
        // 将数据块拼接起来
        var buffer = Buffer.concat(dataBuffer);
        //  将二进制数据转换成字符串格式
        var reqXml = buffer.toString();
        var reqObj = parse.parseString(reqXml, (err, result) => {
            var xml = result.xml;
            // 使用http向图灵机器人服务器发送请求
            var data = "key=free&appid=0&msg="+xml.Content;
            var request = http.request({
                method: "GET",              //发送post请求
                host: "api.qingyunke.com",  //域名地址
                protocal: "http://",        //协议
                port: "80",                 //端口
                path: "/api.php?"+data,           //路径
                headers: {                  //请求头
                    "Content-Type": 'application/json',
                    "Content-Length": Buffer.byteLength(data)
                }
            }, function (response) {           //服务器响应的时候,自动调用(异步执行)
                // res是机器人 返回给你数据
                var bufferList = [];
                response.on("data", function (chunk) {
                    bufferList.push(chunk);
                })

                response.on("end", function () {
                    var robotResult = Buffer.concat(bufferList);
                    console.log();
                    var returnText=JSON.parse(robotResult.toString())
                    var returnMsg = {
                        ToUserName: xml.FromUserName,
                        FromUserName: xml.ToUserName,
                        CreateTime: +new Date(),
                        MsgType: 'text',
                        Content: returnText.content
                    }
                    res.send(build.buildObject(returnMsg));
                })

            })
            // 发送请求
            request.write(data)
            // 使用http请求图灵机器人服务器

        });
    });
});
// 开启服务器
app.listen('8888', () => {
    console.log('server running at http://natappfree.cc');
});